<template>
  <div class="app-container">
    <!-- <div class="filter-container">
      <el-button class="filter-item" type="primary" @click="log = true">查看日志</el-button>
    </div> -->

    <div class="grid">
      <div v-for="(item, index) in devices" :key="index">
        <!-- 移动平台 -->
        <track-axis v-if="item.tag === 'axis'" :device="item" :class="item.online === 0 ? 'offline' : ''" />
        <!-- 控制设备 -->
        <control v-if="item.tag === 'control'" :device="item" :sub="item.sub" :class="item.online === 0 ? 'offline' : ''" />
        <!-- x空气比释动能率计算模块 -->
        <count-x v-if="item.tag === 'count_x'" :device="item" :sub="item.sub" />
        <!-- gamma空气比释动能率计算模块 -->
        <count-gamma v-if="item.tag === 'count_gamma'" :device="item" :sub="item.sub" />
      </div>
    </div>

  </div>
</template>

<script>
import { getDevices } from '@/api/device'
import { getAutos } from '@/api/auto'
import { emqxCheckOnline } from '@/api/emqx'

import TrackAxis from './components/TrackAxis'
import Control from './components/Control'
import CountX from './components/CountX'
import CountGamma from './components/CountGamma.vue'

import { CMD_INFRARED, CMD_DOOR, CMD_SWITCH, CMD_AXIS, CMD_CONTROL, CMD_MOVE, CMD_SYSTEM } from '@/utils/cmd'

export default {
  name: 'XRay',
  components: {
    Control,
    TrackAxis,
    CountX,
    CountGamma
  },
  filters: {
    onlineFilter(status) {
      if (status === 1) {
        return '在线'
      } else {
        return '离线'
      }
    }
  },
  data() {
    return {
      task: {},
      value: true,
      log: false,
      tableKey: 0,
      autos: [],
      devicesLoading: false,
      devices: [],
      deviceInfoShow: false,
      status: {
        temperature: 23.5,
        dampness: 23.5,
        pressure: 100
      },
      sourceTimerChecked: false,
      sourceTimerInterval: 0,
      // 轨道
      dialogTrackVisible: false,
      track: {},
      // 圆盘
      dialogCircleVisible: false,
      circle: { axis: [{ start: 10, split_number: 10 }] }
    }
  },
  activated() {
    this.fetchAll()
  },
  created() {
    this.doSubscribe()
    this.fetchAll()
  },
  methods: {
    fetchAll() {
      // 查询设备在线状态
      emqxCheckOnline().then(response => {
        if (response.code === 200) {
          this.fetchDevices()
        }
      })
    },
    // 查询设备
    fetchDevices() {
      getDevices().then(response => {
        var data = response.data
        if (data === null) {
          data = []
          return false
        }
        for (var i = 0; i < data.length; i++) {
          // 调试用的 device
          // data[i].online = 1
          data[i].value = JSON.parse(data[i].value)
          if (data[i].tag === 'door') { data[i].status = -1 }
          if (data[i].tag === 'infrared') { data[i].status = -1 }
          if (data[i].tag === 'switch') { data[i].status = -1 }
          // 坐标初始化赋值
          if (data[i].tag === 'axis') {
            for (var n = 0; n < data[i].value.axis.length; n++) {
              // data[i].value.axis[n].position = '-----.---'
              data[i].value.axis[n].position = '99999.999'
            }
          }
        }
        data.sort(function(a, b) {
          return a.id - b.id
        })
        this.devices = data
        // 获取智能场景
        // this.fetchAutos()
        // 获取设备状态
        this.getDeviceStatus()
      })
    },
    fetchAutos() {
      console.log('获取智能场景')
      getAutos().then(response => {
        var data = response.data
        if (data === null) {
          data = []
        } else {
          for (var i = 0; i < data.length; i++) {
            data[i].condition = JSON.parse(data[i].condition)
            data[i].run = JSON.parse(data[i].run)
          }
        }
        this.autos = data
        this.checkAuto()
      })
    },
    // 检查智能场景
    checkAuto() {
      console.log('检测智能场景')
      if (this.devices.length > 0 && this.autos.length > 0) {
        var devices = this.devices
        var data = this.autos
        var msg = ''
        for (var i = 0; i < data.length; i++) {
          // 智能场景使能情况下
          if (data[i].enable === 1) {
            var device = null
            var d = 0
            var conditions = data[i].condition
            var runs = data[i].run
            var c_err_msg = ''
            var isExist = false
            for (var c = 0; c < conditions.length; c++) {
              isExist = false
              for (d = 0; d < devices.length; d++) {
                device = devices[d]
                if (device.sn === conditions[c].sn) {
                  isExist = true
                  if (device.online === 0) {
                    c_err_msg += '<li>场景中的条件：' + '[' + device.name + '(sn:' + device.sn + ')]' + '设备离线</li>'
                    break
                  }
                }
              }
              if (!isExist) {
                c_err_msg += '<li>场景中的条件：' + '[' + conditions[c].name + '(sn:' + conditions[c].sn + ')]' + '设备不存在</li>'
              }
              console.log('条件：' + '[' + conditions[c].name + '(sn:' + conditions[c].sn + ')]' + isExist)
            }
            for (var r = 0; r < runs.length; r++) {
              isExist = false
              for (d = 0; d < devices.length; d++) {
                device = devices[d]
                if (device.sn === runs[r].sn) {
                  isExist = true
                  if (device.online === 0) {
                    c_err_msg += '<li>场景中的动作：' + '[' + device.name + '(sn:' + device.sn + ')]' + '设备离线</li>'
                    break
                  }
                }
              }
              if (!isExist) {
                c_err_msg += '<li>场景中的动作：' + '[' + runs[r].name + '(sn:' + runs[r].sn + ')]' + '设备不存在</li>'
              }
              console.log('动作：' + '[' + runs[r].name + '(sn:' + runs[r].sn + ')]' + isExist)
            }
            if (c_err_msg !== '') {
              msg += '<h4>智能场景：[' + data[i].name + '] 失效, 原因：</h4> ' + c_err_msg + '<br/>'
            }
          }
        }
        if (msg.length === 0) {
          msg = '连锁正常'
          this.$confirm(msg, '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            title: '提示',
            type: 'success'
          })
        } else {
          this.$confirm(msg, '提示', {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            title: '提示',
            type: 'warning'
          })
        }
      }
    },

    getDeviceStatus() {
      for (var i = 0; i < this.devices.length; i++) {
        if (this.devices[i].online === 1) {
          if (this.devices[i].tag === 'infrared') {
            // 查询红外设备状态
            this.InfraredGetPeople(this.devices[i])
          }
          if (this.devices[i].tag === 'door') {
            // 查询门禁设备状态
            this.DoorGet(this.devices[i])
          }
          if (this.devices[i].tag === 'switch') {
            // 查询门禁设备状态
            this.SwitchGet(this.devices[i])
          }
          if (this.devices[i].tag === 'axis') {
            // 查询设备位置
            this.AxisGetPositions(this.devices[i])
          }
          if (this.devices[i].tag === 'control') {
            // 查询控制检测设备IO口状态
            this.ControlGetPin(this.devices[i])
          }
        }
      }
    },

    // 显示设备信息
    deviceInfo(item) {
      this.deviceInfoShow = true
      console.log(item)
    },

    // 红外获取是否有人
    InfraredGetPeople(item) {
      item.value.people = 0
      var message = {
        code: CMD_INFRARED.get_people.toString(),
        msg: '0'
      }
      this.publish(item.sub, JSON.stringify(message))
    },

    // 门禁获取是否开启
    DoorGet(item) {
      item.value.door = 0
      this.publish(item.sub, JSON.stringify({
        code: CMD_DOOR.get_door.toString(),
        msg: '0'
      }))
    },

    // 源控获取状态
    SwitchGet(item) {
      item.value.switch = 0
      this.publish(item.sub, JSON.stringify({
        code: CMD_SWITCH.get_switch.toString(),
        msg: '0'
      }))
    },

    // 查询控制检测设备IO口状态
    ControlGetPin(item) {
      item.value.switch = 0
      this.publish(item.sub, JSON.stringify({
        code: CMD_CONTROL.get_pin.toString(),
        msg: '0'
      }))
    },

    // 获取所有轴位置
    AxisGetPositions(item) {
      console.log('移动轴获取位置...')
      this.publish(item.sub, JSON.stringify({
        code: CMD_MOVE.get_positions.toString(),
        msg: '1'
      }))
    },

    // axis轴运动处理
    axisDeal(device, aswcode, aswmsg) {
      for (var i = 0; i < CMD_AXIS.length; i++) {
        if (CMD_AXIS[i].set_position === aswcode) {
          this.$message({ message: '[' + device.name + ']-' + '[' + device.value.axis[i].name + ']' + '重置位置成功', type: 'success' })
          // this.publish(device.sub, JSON.stringify({ code: CMD_AXIS[i].get_position.toString(), msg: '1' }))
        }
        if (CMD_AXIS[i].move_pos === aswcode) {
          this.$message({ message: '[' + device.name + ']-' + '[' + device.value.axis[i].name + ']' + '开始移动', type: 'success' })
          break
        }
        if (CMD_AXIS[i].get_status === aswcode) {
          device.value.axis[i].status = parseInt(aswmsg)
          break
        }
        if (CMD_AXIS[i].get_position === aswcode) {
          // 下面传上来是um, 位置转换为mm, 系数为1000
          var position = parseFloat(aswmsg) / 1000
          // 更新位置
          device.value.axis[i].position = position
          // 比对当前位置和预设位置, 到达指定位置后显示位置名称
          var positions = device.value.axis[i].positions
          var isArrived = false
          for (var p = 0; p < positions.length; p++) {
            var err = Math.abs(position - parseFloat(positions[p].value))
            if (err < 0.2) {
              device.value.axis[i].position_name = positions[p].name
              console.log('运动到预设指定位置：' + positions[p].name)
              isArrived = true
              break
            }
          }
          if (isArrived) {
            this.$message({
              message: '[' + device.name + ']->' + '(' + device.value.axis[i].name + ')' + '已移动到预设位置：' + '[' + device.value.axis[i].position_name + '] >>>' + device.value.axis[i].position,
              type: 'success'
            })
          } else {
            device.value.axis[i].position_name = '无'
            this.$message({
              message: '[' + device.name + ']->' + '(' + device.value.axis[i].name + ')' + '移动到位置:' + device.value.axis[i].position,
              type: 'success',
              duration: 500
            })
          }
          // 有任务时
          if (this.task.done === false) {
            this.task.once_done = true
          }
          // 更新x空气比释动能率计算所需位置
          this.CountXsetDistance(device.value.axis[i].name, position)
          // 更新gamma空气比释动能率计算所需位置
          this.CountGammaSetDistance(device.value.axis[i].name, position)
          break
        }
      }
    },

    // 红外门禁检查控制器设备
    controlDeal(device, aswcode, aswmsg) {
      if (CMD_CONTROL.get_pin === parseInt(aswcode)) {
        var key0 = parseInt(aswmsg[0])
        var key1 = parseInt(aswmsg[1])
        var key2 = parseInt(aswmsg[2])
        var key3 = parseInt(aswmsg[3])
        var infrared = parseInt(aswmsg[4])
        var door = parseInt(aswmsg[5])
        var relay0 = parseInt(aswmsg[6])
        var relay1 = parseInt(aswmsg[7])
        var chain = parseInt(aswmsg[8])

        // 更新io口状态
        device.value.key0.value = key0
        device.value.key1.value = key1
        device.value.key2.value = key2
        device.value.key3.value = key3
        device.value.infrared.value = infrared
        device.value.door.value = door
        device.value.relay0.value = relay0
        device.value.relay1.value = relay1

        device.value.chain = chain

        console.log('key0:' + key0)
        console.log('key1:' + key1)
        console.log('key2:' + key2)
        console.log('key3:' + key3)
        console.log('infrared:' + infrared)
        console.log('door:' + door)
        console.log('relay0:' + relay0)
        console.log('relay1:' + relay1)
        console.log('chain:' + chain)
        this.$message({
          message: '[' + device.name + ']' + '状态发生变化',
          type: 'warning',
          duration: 500
        })
      }
      if (CMD_CONTROL.get_environment === parseInt(aswcode)) {
        // 自动更新数据和计算
        if (device.value.auto) {
          var press = parseFloat(aswmsg[0])
          var temperature = parseFloat(aswmsg[1])
          var humidity = parseFloat(aswmsg[2])
          device.value.press = press
          device.value.temperature = temperature
          device.value.humidity = humidity
          console.log('压力:' + press + '温度：' + temperature + '湿度:' + humidity)
        }
      }
    },

    // x空气比释动能率参数更新-距离
    CountXsetDistance(axis_name, position) {
      console.log('空气比释动能率参数更新~距离')
      console.log('axis_name: ', axis_name, 'position: ', position)
      for (var x = 0; x < this.devices.length; x++) {
        if (this.devices[x].tag === 'count_x') {
          if (this.devices[x].value.auto) {
            console.log('axis_name: ', axis_name, 'position: ', position)
            if (axis_name === this.devices[x].value.condition.DistanceAxisName) {
              // position 单位从mm转换为m
              this.devices[x].value.condition.Distance = (position / 1000).toFixed(3)
              console.log('更新距离为：', this.devices[x].value.condition.Distance)
            }
          }
          break
        }
      }
    },

    // 伽马空气比释动能率参数更新-距离
    CountGammaSetDistance(axis_name, position) {
      console.log('空气比释动能率参数更新~距离')
      console.log('axis_name: ', axis_name, 'position: ', position)
      for (var x = 0; x < this.devices.length; x++) {
        if (this.devices[x].tag === 'count_gamma') {
          if (this.devices[x].value.auto) {
            console.log('axis_name: ', axis_name, 'position: ', position)
            if (axis_name === this.devices[x].value.condition.DistanceAxisName) {
              // position 单位从mm转换为m
              this.devices[x].value.condition.Distance = (position / 1000).toFixed(3)
              console.log('更新距离为：', this.devices[x].value.condition.Distance)
            }
          }
          break
        }
      }
    },

    // mqtt相关操作
    doSubscribe() {
      this.subscribe('fsc/#')
    },

    subscribe(val) {
      console.log('订阅主题')
      console.log(val)
      this.$mqtt.subscribe(val)
    },
    publish(topic, message) {
      console.log('推送mqtt消息')
      console.log('topic:' + topic)
      console.log('message:' + message)
      this.$mqtt.publish(topic, message)
    }
  },
  mqtt: {
    '#'(data, topic) {
      console.log('收到mqtt消息:')
      console.log('topic:' + topic)
      console.log('payload: ' + String.fromCharCode.apply(null, data))
      try {
        var info = JSON.parse(data)
        console.log('json格式：')
        console.log(info)
        var aswcode = parseInt(info.aswcode)
        var aswmsg = info.aswmsg
        var i = 0
        for (i = 0; i < this.devices.length; i++) {
          var device = this.devices[i]
          if (aswcode === CMD_SYSTEM.online) {
            if (device.sn === info.clientid) {
              this.$message({ message: '[' + device.name + ']-' + '在线状态变化', type: 'error' })
              device.online = parseInt(info.aswmsg)
            }
          }
          // 设备离线，不处理状态变化
          // if (device.online === 0) {
          //   continue
          // }
          if (device.pub === topic) {
            // 红外
            if (device.tag === 'infrared') {
              if (aswcode === CMD_INFRARED.get_people) {
                this.$message({ message: '[' + device.name + ']-' + '变化', type: 'warning' })
                device.status = parseInt(aswmsg)
              }
            }
            if (device.tag === 'door') {
              if (aswcode === CMD_DOOR.get_door) {
                this.$message({ message: '[' + device.name + ']-' + '变化', type: 'warning' })
                device.status = parseInt(aswmsg)
              }
            }
            if (device.tag === 'switch') {
              if (aswcode === CMD_SWITCH.get_switch) {
                this.$message({ message: '[' + device.name + ']-' + '变化', type: 'error' })
                device.status = parseInt(aswmsg)
              }
            }
            // 轨道数据处理
            if (device.tag === 'axis') {
              console.log('设备信息处理->轨道设备')
              this.axisDeal(device, aswcode, aswmsg)
            }
            // 控制设备处理
            if (device.tag === 'control') {
              console.log('设备信息处理->连锁控制设备')
              this.controlDeal(device, aswcode, aswmsg)
            }
          }
        }
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container{
  height: 1200px;
  background-image: url(../../../assets/login-bg.jpg);
  background-size: 100%;
}

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-row-gap: 10px;
  grid-column-gap: 10px;
  grid-auto-flow: row dense;
  // grid-auto-flow: column dense;
}

.body-flex {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  // align-content: flex-start;
}

.row {
  display:flex;
  display:-webkit-flex;/*Safari*/
  justify-content:space-around;/*水平排布方式*/
  align-items:center;/*垂直对齐方式*/
}

.offline {
  -webkit-filter: grayscale(100%);
  -moz-filter: grayscale(100%);
  -ms-filter: grayscale(100%);
  -o-filter: grayscale(100%);
  filter: grayscale(100%);
  filter: gray;
  pointer-events: none; // 屏蔽所有活动
}

.device {
  // margin-top: 18px;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px 10px;

  .dev-axis {
    grid-column-start: 1;
    grid-row-start: 1;
    grid-row-end: 3;
  }

  .dev-control {
    grid-column-start: 2;
    grid-row-start: 1;
    grid-row-end: 4;
  }

  .dev-radio {
    grid-column-start: 2;
    grid-row-start: 1;
    grid-row-end: 4;
  }

}

</style>
